package org.example.service;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.example.config.Configurations;
import org.example.dto.SqlData;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;

public class XmlBuilderService {


    private Configurations configuration;

    public XmlBuilderService(Configurations configuration) {
        this.configuration = configuration;
    }

    /**
     * 我在这里把地址写死了，当然可以在配置文件当中设置
     * @throws DocumentException
     */
    public void parse() throws DocumentException {
        File folder = new File("src/main/resources/mapper");
        File[] files = folder.listFiles((dir,name)->{
            return name.endsWith(".xml");
        });

        for (File file : files) {
            SAXReader saxReader = new SAXReader();
            Document read = saxReader.read(file);


            Element readElements = read.getRootElement();

            //主标签上的属性
            String namespace = readElements.attributeValue("namespace");

            //主标签下的所有标签
            List<Element> elements = readElements.elements();

            //按照对应的namespace去找这个mapper对应的方法
            for (Element element : elements) {
                String name = element.getName();
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String parameterType = element.attributeValue("parameterType");
                String textTrim = element.getTextTrim();
                //解析为相应的数据，保存到configurations当中
                SqlData sqlData = new SqlData();
                sqlData.setId(id);
                sqlData.setSql(textTrim);
                sqlData.setParameterType(parameterType);
                sqlData.setResultType(resultType);
                sqlData.setType(name);
                String key = namespace+"."+id;
                System.out.println(key);
                configuration.getMap().put(namespace+"."+id,sqlData);
            }

        }
    }
}
